﻿Imports Darkorbit
Imports Darkorbit.Const
Imports System.Web.Script.Serialization
Imports System.IO
Imports System.Threading

Public Class frmMain
#Region "Getter / Setter"
    Private _AccountList As New List(Of Account)
    Public Property AccountList As List(Of Account)
        Get
            Return _AccountList
        End Get
        Set(value As List(Of Account))
            _AccountList = value
        End Set
    End Property

    Private _HitTestInfo As DataGridView.HitTestInfo
    Public ReadOnly Property HitTestInfo As DataGridView.HitTestInfo
        Get
            Return _HitTestInfo
        End Get
    End Property

    Private isLoginIn As Boolean = False
    Private _AccountTabPages As New List(Of AccountControl)
#End Region


#Region "Add account to database / datagridview events"
    Function generatePasswordString(ByVal input As String) As String
        Dim ret As String = String.Empty
        For i As Integer = 0 To input.Length - 1
            ret &= "*"
        Next
        Return ret
    End Function

    Private Sub dgvAccounts_MouseClick(sender As Object, e As MouseEventArgs) Handles dgvAccounts.MouseClick
        If isLoginIn = False Then
            _HitTestInfo = dgvAccounts.HitTest(e.X, e.Y)
            If e.Button = Windows.Forms.MouseButtons.Right Then
                cmsDgvAccounts.Show(MousePosition)
            End If
        End If

    End Sub

    Private Sub addAccountToolStripMenuItem1_Click(sender As Object, e As EventArgs) Handles AddAccountToolStripMenuItem1.Click
        Dim f As New frmAccAccount(Me)
        If f.ShowDialog = Windows.Forms.DialogResult.OK Then
            refreshAccountDatabase()
        End If
    End Sub

    Sub refreshAccountDatabase()
        dgvAccounts.Rows.Clear()
        For Each item As Account In _AccountList
            dgvAccounts.Rows.Add(item.Username, generatePasswordString(item.Password), item.Server)
        Next
    End Sub

    Private Sub deleteAccountToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles DeleteAccountToolStripMenuItem.Click
        If _HitTestInfo.RowIndex > -1 Then
            _AccountList.RemoveAt(_HitTestInfo.RowIndex)
            refreshAccountDatabase()
        End If
    End Sub
#End Region

    Private Sub loginToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LoginToolStripMenuItem.Click
        With New Thread(AddressOf initializeLogin)
            .IsBackground = True
            .Start()
        End With
    End Sub

    Sub initializeLogin()
        isLoginIn = True
        If _HitTestInfo.RowIndex > -1 Then
            If _AccountList(_HitTestInfo.RowIndex).login Then
                _AccountList(_HitTestInfo.RowIndex).initialize()
                Invoke(Sub()
                           Dim tb As New TabPage
                           tb.Name = "tbAccount" & _AccountList(_HitTestInfo.RowIndex).Username
                           tb.Text = _AccountList(_HitTestInfo.RowIndex).Username
                           Dim uc As New AccountControl(_AccountList(_HitTestInfo.RowIndex))
                           _AccountTabPages.Add(uc)
                           uc.Parent = tb
                           tb.BackColor = SystemColors.Control
                           tcMain.TabPages.Add(tb)
                           tcMain.SelectedTab = tb
                       End Sub)

            Else
                MessageBox.Show("Error, can't login to " & _AccountList(_HitTestInfo.RowIndex).Username & "!")
            End If
        End If
        isLoginIn = False
    End Sub

    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
        Try
            Dim x As New JavaScriptSerializer()
            Dim acc As New List(Of AccountData)
            For Each item In _AccountList
                Dim h As New AccountData()
                h.Username = item.Username
                h.Password = Encryption.CryptCaesar(item.Password)
                h.Server = item.Server
                acc.Add(h)
            Next
            Dim s As String = x.Serialize(acc)
            IO.File.WriteAllText("Accounts.json", s)
        Catch ex As Exception
        End Try
    End Sub

    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        If File.Exists("Accounts.json") Then
            _AccountList = New List(Of Account)

            Dim x As New JavaScriptSerializer()
            Dim s As List(Of AccountData) = x.Deserialize(Of List(Of AccountData))(IO.File.ReadAllText("Accounts.json"))

            For Each item In s
                Dim a As New Account(item.Username, Encryption.DeCryptCaesar(item.Password), item.Server)
                _AccountList.Add(a)
            Next
            refreshAccountDatabase()
        End If



    End Sub

    Private Sub LogoutToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles LogoutToolStripMenuItem.Click
        If _HitTestInfo.RowIndex > -1 Then
            For Each t In _AccountTabPages
                If t.Account.Username = _AccountList(_HitTestInfo.RowIndex).Username Then
                    t.tmrRefreshUserData.Enabled = False
                    For Each u As TabPage In tcMain.TabPages
                        If u.Text = _AccountList(_HitTestInfo.RowIndex).Username Then
                            tcMain.TabPages.Remove(u)
                        End If
                    Next
                    _AccountTabPages.Remove(t)
                    t.Dispose()
                    Exit For
                End If
            Next
        End If
    End Sub

    Private Sub dgvAccounts_ColumnAdded(sender As Object, e As DataGridViewColumnEventArgs) Handles dgvAccounts.ColumnAdded
        e.Column.SortMode = DataGridViewColumnSortMode.NotSortable
    End Sub
End Class